import React, { PropsWithChildren, ReactElement, SyntheticEvent } from 'react'

interface Props<T> {
  text: T;
  onCopy: (
    result: Promise<{
      status: boolean;
      text: T;
    }>
  ) => any
}

const copy = async (text: string) => {
  let status;
  try {
    await window.navigator.clipboard.writeText(text)
    status = true
  } catch (error) {
    status = false
    console.error(error);
  }
  const result = {
    status,
    text,
  }
  return result
}

const CopyToClipboard = (
  { children, text, onCopy }: PropsWithChildren<Props<string>>
) => {
  const reactElement = React.Children.only(children) as ReactElement
  const { onClick } = reactElement.props

  const newOnClick = (event: SyntheticEvent) => {
    if (typeof onClick === 'function') {
      onClick(event)
    }

    const resultPromise = copy(text)
    onCopy(resultPromise)
  }

  const clonalElement = React.useMemo(() => {
    return React.cloneElement(reactElement, {
      ...reactElement.props,
      onClick: newOnClick
    })
  }, [reactElement])
  return clonalElement
}

export default CopyToClipboard
